#include "ProjectManager.hpp"
#include <fmt/format.h>
#include <sstream>
#include <stdexcept>

std::vector<std::string> SplitStringToVector(const std::string & str)
{
  if(str.size()==0)
    return std::vector<std::string>();

  std::stringstream ss(str);
  std::string res;
  std::vector<std::string> res_list;
  while(std::getline(ss,res,','))
  {
    if(res.back()=='\0')
      res.pop_back();
    res_list.push_back(res);
  }
  return std::move(res_list);
}

ProjectManager::ProjectManager()
{
  messageQueue.reset(new POSIX_MessageQueue("/HBTY_MSGQUEUE_PROJECT"));
}

ProjectManager::~ProjectManager()
{

}

bool ProjectManager::CreateProject(const std::string & Name,const std::string & Decribe)
{
  messageQueue->SendData(fmt::format("Create Project {} {}",Name,Decribe));
  if(strcmp(messageQueue->ReceiveData().c_str(),"True")==0)
    return true;
  else return false;
}

bool ProjectManager::CreateTask(const std::string & project_name,const std::string & task_name)
{
  messageQueue->SendData(fmt::format("Create Task {} {}",project_name,task_name));
  if(strcmp(messageQueue->ReceiveData().c_str(),"True")==0)
    return true;
  else return false;
}

std::vector<std::string> ProjectManager::GetProjectList()
{
  messageQueue->SendData(fmt::format("Get Project"));
  return SplitStringToVector(messageQueue->ReceiveData());
}

std::vector<std::string> ProjectManager::GetTaskList(const std::string & project_name)
{
  messageQueue->SendData(fmt::format("Get Task {}",project_name));
  return SplitStringToVector(messageQueue->ReceiveData());
}

std::vector<std::string> ProjectManager::GetTaskVideo(const std::string & project_name,const std::string & task_name)
{
  messageQueue->SendData(fmt::format("Get Task Video {} {}",project_name,task_name));
  return SplitStringToVector(messageQueue->ReceiveData());
}

bool ProjectManager::CreateTaskVideo(const std::string & project_name,const std::string & task_name,const std::string & CameraID,const std::string & Videoname)
{
  messageQueue->SendData(fmt::format("Create Task Video {} {} {} {}",project_name,task_name,CameraID,Videoname));
  if(!strcmp(messageQueue->ReceiveData().c_str(),"True"))
    return true;
  else
    return false;
}

std::string ProjectManager::GetTaskVideoPath(const std::string & project_name,const std::string & task_name,const std::string & CameraID)
{
  messageQueue->SendData(fmt::format("Get Task Video Path {} {} {}",project_name,task_name,CameraID));
  return messageQueue->ReceiveData();
}

std::string ProjectManager::GetTaskPath(const std::string & project_name,const std::string & task_name)
{
  messageQueue->SendData(fmt::format("Get Task Path {} {}",project_name,task_name));
  return messageQueue->ReceiveData();
}

int ProjectManager::refreshVideoList(const std::string & project_name,const std::string & task_name)
{
  return 2;
}
